package com.aabte.lock.jedis.v1;

import redis.clients.jedis.Jedis;

public class ThreadTask extends Thread {

    private Jedis jedis;
    private String lockKey;
    private String requestId;
    private long expireTime;

    public ThreadTask(Jedis jedis, String lockKey, String requestId, long expireTime) {
        this.jedis = jedis;
        this.lockKey = lockKey;
        this.requestId = requestId;
        this.expireTime = expireTime;
    }

    @Override
    public void run() {
        RedisPessimisticLock lock = new RedisPessimisticLock(jedis, lockKey, requestId, expireTime);
        boolean getLockResult = lock.tryGetDistributedLock();
        if (!getLockResult) {
            System.err.println(String.format("%s 获取锁失败！lockKey: %s, requestId: %s", Thread.currentThread().getName(), lockKey, requestId));
            return;
        } else {
            System.out.println(String.format("%s 获取锁成功！lockKey: %s, requestId: %s", Thread.currentThread().getName(), lockKey, requestId));
            try {
                // 业务处理...
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                // nothing
            }
            lock.releaseDistributedLock();
        }
        jedis.close();
    }
}
